package socket.httpserver.redirect;

import java.io.*;
import java.net.Socket;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

public class RedirectThread extends Thread {
    private static final Logger logger = Logger.getLogger("RedirectThread");

    private final Socket connection;
    private final String newSite;

    public RedirectThread(Socket s, String newSite) {
        this.connection = s;
        this.newSite = newSite;
    }

    @Override
    public void run() {
        try {
            Writer out = new BufferedWriter(
                            new OutputStreamWriter(
                                    connection.getOutputStream(), "US-ASCII"
                            )
            );

            Reader in = new InputStreamReader(
                    new BufferedInputStream(connection.getInputStream())
            );

            // 只读取一行，这是我们需要的全部内容
            StringBuilder request = new StringBuilder(80);
            while(true) {
                int c = in.read();
                if(c == '\r' || c == '\n' || c == -1) {
                    break;
                }
                request.append((char)c);
            }

            String get = request.toString();
            String[] pieces = get.split("\\w");
            String theFile = pieces[1];

            // HTTP/1.0 则发送一个MIME首部
            if(get.indexOf("HTTP") != -1) {
                out.write("HTTP/1.0 302 FOUND\r\n");
                Date now = new Date();
                out.write("Date: " + now + "\r\n");
                out.write("Server: Redirector 1.1\r\n");
                out.write("Location: " + newSite + theFile + "\r\n");
                out.write("Content-type:text/html\r\n\r\n");
                out.flush();
            }

            // 并不是所有的浏览器都支持重定向，所以我们需要生成HTML指出文档转移到哪里
            /*out.write("<HTML><HEAD><TITLE>Document moved</TITLE></HEAD>\r\n");
            out.write("<BODY><H1>Document moved</H1>\r\n");
            out.write("The documet " + theFile
                + " has moved to\r\n<A HREF=\"" + newSite + theFile + "\">"
                + newSite + theFile
                + "</A>.\r\n Please update your bookmarks<P>");
            out.write("</BODY></HTML>\r\n");
            out.flush();*/

            StringBuilder html = new StringBuilder();
            html.append("<html><head><title>Document Moved</title></head>");
            html.append("<body>");
            html.append("The site has moved,please update your bookmarket,and click the hyper link <a href='"+newSite+"'>"+theFile+"</a>!");
            html.append("</body></html>");
            out.write(html.toString());
            out.flush();
            logger.log(Level.INFO, "Redirected " + connection.getRemoteSocketAddress());
        } catch (IOException e) {
            logger.log(Level.WARNING, "Error talking to " + connection.getRemoteSocketAddress(), e);
        } finally {
            try{
                connection.close();
            } catch (IOException e){}
        }
    }
}
